package net.hky365.shop.module.bpm.framework.flowable.core.listener;

import net.hky365.shop.framework.common.util.json.JsonUtils;
import net.hky365.shop.module.bpm.framework.flowable.core.util.FlowableUtils;
import net.hky365.shop.module.bpm.service.task.BpmProcessInstanceService;
import com.google.common.collect.ImmutableSet;
import jakarta.annotation.Resource;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * 监听 {@link ProcessInstance} 的状态变更，更新其对应的 status 状态
 *
 * @author jason
 */
@Component
public class BpmProcessInstanceEventListener extends AbstractFlowableEngineEventListener {

    public static final Set<FlowableEngineEventType> PROCESS_INSTANCE_EVENTS = ImmutableSet.<FlowableEngineEventType>builder()
            .add(FlowableEngineEventType.PROCESS_COMPLETED)
            .build();

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private BpmProcessInstanceService processInstanceService;

    public BpmProcessInstanceEventListener(){
        super(PROCESS_INSTANCE_EVENTS);
    }

    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        //获取表单内容
        ProcessInstance instance = (ProcessInstance)event.getEntity();
        instance.getProcessVariables();
//        Map<String, Object> formVariable = FlowableUtils.getProcessInstanceFormVariable(instance);
//        System.out.println(JsonUtils.toJsonByte(formVariable));
        processInstanceService.processProcessInstanceCompleted((ProcessInstance)event.getEntity());
    }

}
